package com.yanqu.road.server.manager.douluodalu;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.CrossActivityDetail;
import com.yanqu.road.entity.activity.douluodalu.DouLuoDaLuUserEvent;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuRegionInfo;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuHelpRecordData;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuPatronsBattleData;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuUserData;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.mina.util.ConcurrentHashSet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DouLuoActivityGroup {
    private int activityId;
    private Map<Integer, CrossDouLouDaLuActivity> activityMap = new ConcurrentHashMap<>();

    public DouLuoActivityGroup(int activityId) {
        this.activityId = activityId;
    }

    public CrossDouLouDaLuActivity getActivityOrNull(int groupId) {
        return activityMap.get(groupId);
    }

    public int getActivityId() {
        return activityId;
    }

    public CrossDouLouDaLuActivity getActivity(int groupId) {
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            return null;
        }
        CrossDouLouDaLuActivity activity = activityMap.get(groupId);
        if (activity == null) {
            synchronized (activityMap) {
                activity = activityMap.get(groupId);
                if (activity == null) {
                    activity = new CrossDouLouDaLuActivity(activityId, groupId);
                    //初始每日重置
                    CrossActivityDetail crossActivityDetail = ActivityMgr.getCrossActivityDetail(activityId, groupId, true);
                    crossActivityDetail.setParam1(DateHelper.getCurrentTime()/1000);
                    activityMap.put(groupId, activity);
                }
            }
        } else {
            //初始npc血量
            if (activity.isCreateTeamPeriodLastNMin(1)) {
                activity.initMonsterDynamicBlood(false);
            }

            CrossActivityDetail resetDetail = ActivityMgr.getCrossActivityDetail(activityId, groupId, true);
            //每日重置
            if (resetDetail.getParam1() == 0) {
                resetDetail.setParam1(DateHelper.getCurrentTime()/1000);
            } else {
                // param1表示上次刷新活动区域时间
                if (DateHelper.getDiffDayNum(resetDetail.getParam1()) > 0) {
                    synchronized (activity) {
                        // param1表示上次刷新活动区域时间
                        if (DateHelper.getDiffDayNum(resetDetail.getParam1()) > 0) {
                            activity.getAreaUserMap().clear();
                            for (Map.Entry<Long, DouLuoDaLuUserData> userDataEntry : activity.getAllUserMap().entrySet()) {
                                DouLuoDaLuUserData userData = userDataEntry.getValue();

                                userData.setCanAttackUserSet(new ConcurrentHashSet<>());
                                resetUserDataForChangeRegion(userData, activity.getConfig().getFirstRegionInfo());
                            }
                            long restTime = System.currentTimeMillis() / 1000;
                            for (Map.Entry<Long, DouLuoDaLuPatronsBattleData> battleDataEntry : activity.getBattleDataMap().entrySet()) {
                                DouLuoDaLuPatronsBattleData battleData = battleDataEntry.getValue();
                                battleData.setBeHitTimes(0);
                                battleData.setResetTime(restTime);
                            }
                            resetDetail.setParam1(System.currentTimeMillis() / 1000);
                            //如果组队期超过24小时，组队期后的初始化则由玩家触发，不然第一天会出现提前初始血量
                            if (!activity.isCreateTeamPeriod()) {
                                activity.initMonsterDynamicBlood(true);
                            }
                        }
                    }
                }
            }
        }
        return activity;
    }

    /**
     * 重置玩家数据/区域变更
     *
     * @param regionInfo 目标区域
     */
    public void resetUserDataForChangeRegion(DouLuoDaLuUserData userData, DouLuoDaLuRegionInfo regionInfo) {
        userData.setEntryRegionTime(DateHelper.getCurrentSecond());
        userData.setFromRegionId(userData.getRegionId());
        userData.setRegionId(regionInfo.getRegionId());
        //重置玩家血量及保护时间
        userData.setTotalBlood(userData.getHunLi());
        userData.setBlood(userData.getTotalBlood());
        //清理事件统计,保留七怪保底计数
        Map<Integer, Integer> qiGuaiMap = new ConcurrentHashMap<>();

        userData.setFinishEventMap(qiGuaiMap);
        //重置事件
        userData.setEvent(new DouLuoDaLuUserEvent());
        DouLuoDaLuHelpRecordData helpRecordData = userData.getCurrentHelpRecordData();
        if (helpRecordData != null) {
            updateHelpDataKillInfo(helpRecordData, -1, 0, userData);
        }
        userData.setCurrentHelpRecordData(null);
    }

    /**
     * 更新协助记录击杀信息
     */
    public void updateHelpDataKillInfo(DouLuoDaLuHelpRecordData helpRecordData, long killUserId, long killTime, DouLuoDaLuUserData helpRecordOwner) {
        if (helpRecordData.getKilledUserId() == 0) {
            helpRecordData.setKillTime(killTime);
            helpRecordData.setKilledUserId(killUserId);
            if (helpRecordData.getUserId() == killUserId) {
                helpRecordData.setIsReceived(true);
            }
        }
        if (helpRecordData == helpRecordOwner.getCurrentHelpRecordData()) {
            helpRecordOwner.setCurrentHelpRecordData(null);
        }
    }

    public void save() {
        for (CrossDouLouDaLuActivity activity : activityMap.values()) {
            try {
                activity.save();
            } catch (Exception e) {
                CrossDouLuoDaLuMgr.getLogger().error("activity {} groupId {} save err", activity.getActivityId(), activity.getGroupId(), e.getCause());
            }

        }
    }
}
